﻿package net.wangit.user.group;

import java.util.Map;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.framework.util.MapListUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.user.privilege.PrivilegeUtil;
import net.wangit.util.Checker;


public class UserGroupFactory {

	private static final String SQL_USERGROUP = "select * from AGROUP where groupid=?";
	private static final String SQL_ROLES = "select * from AGROUPROLE where groupid=?";
	private static final String SQL_PRIVILEGES = "select * from AROLEPRIVILEGE where roleid not in (select roleid from AROLE where enabled=0) and roleid in (select roleid from AGROUPROLE where groupid=?)";

	public UserGroupFactory() {
	}

	public static UserGroup getUserGroup(String userGroupId) throws Exception {
		UserGroup userGroup = UserGroupCache.get(userGroupId);
		if (userGroup == null) {
			userGroup = createUserGroup(userGroupId);
			UserGroupCache.put(userGroupId, userGroup);
		}
		return userGroup;
	}

	private static UserGroup createUserGroup(String groupId) throws Exception {
		DB db = DBFactory.getDB();
		MapList list = db.query("select * from AGROUP where groupid=?",
				groupId, 2);
		if (Checker.isEmpty(list)) {
			return null;
		} else {
			Row row = list.getRow(0);
			UserGroup group = new UserGroup(groupId);
			group.setName(row.get("groupname"));
			group.setValid("1".equals(row.get("enabled")));
			group.setRoles(getRoles(db, groupId));
			group.setPrivileges(getPrivileges(db, groupId));
			return group;
		}
	}

	private static String[] getRoles(DB db, String groupId) throws Exception {
		MapList list = db.query("select * from AGROUPROLE where groupid=?",
				groupId, 2);
		return MapListUtil.getArray(list, "roleid");
	}

	private static Map getPrivileges(DB db, String groupId) throws Exception {
		MapList list = db
				.query(
						"select * from AROLEPRIVILEGE where roleid not in (select roleid from AROLE where enabled=0) and roleid in (select roleid from AGROUPROLE where groupid=?)",
						groupId, 2);
		return PrivilegeUtil.getPrivileges(list);
	}
}
